/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.command;

import org.eclipse.draw2d.geometry.Rectangle;

/**
 * Updates the margins for a (multicovering) interaction fragment. The margins
 * measure the space from the left edge of the fragment to the leftmost covered
 * lifeline and the space from the right edge of the fragment to the rightmost
 * covered lifeline.
 * <p>
 * The following attributes must be set before the command can run successfully:
 * </p>
 * <ul>
 * <li>Fragment
 * <li>LeftMargin
 * <li>RightMargin
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class SetFragmentMarginsCommand extends AbstractMarginCommand {

	private int leftMargin;
	private int rightMargin;
	private Rectangle oldBounds;
	private Rectangle newBounds;

	public void setLeftMargin(int leftMargin) {
		this.leftMargin = leftMargin;
	}

	public void setRightMargin(int rightMargin) {
		this.rightMargin = rightMargin;
	}

	public Rectangle getNewBounds() {
		return newBounds.getCopy();
	}

	@Override
	public void execute() {
		final int[] margins = getMargins(fragment);
		final int left = margins[0];
		final int right = margins[1];

		oldBounds = new Rectangle(fragment.getPosition(), fragment.getSize());
		newBounds = new Rectangle(
				oldBounds.x - left + leftMargin,
				oldBounds.y,
				oldBounds.width - (-left + right) + (-leftMargin + rightMargin),
				oldBounds.height);
	}

	@Override
	public void undo() {
		fragment.setSize(oldBounds.getSize());
		fragment.setPosition(oldBounds.getLocation());
		oldBounds = null;
	}

	@Override
	public void redo() {
		execute();
	}

	@Override
	public void dispose() {
		super.dispose();
		oldBounds = null;
	}
}
